using AutoMapper;

namespace ZeroSum.Extend.Mapper.Annotations;

/// <summary>
///     指定映射目标（可以创建多个注解）
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct, AllowMultiple = true)]
public class AutoMapToAttribute : Attribute
{
    public AutoMapToAttribute(Type targetType)
    {
        TargetType = targetType;
    }

    /// <summary>
    ///     目标类型
    /// </summary>
    public Type TargetType { get; }

    /// <summary>
    ///     If set to true, construct the destination object using the service locator.
    /// </summary>
    public bool ConstructUsingServiceLocator { get; set; }

    /// <summary>
    ///     限制最深的深度
    /// </summary>
    public int MaxDepth { get; set; }

    /// <summary>
    ///     If set to true, preserve object identity. Useful for circular references.
    /// </summary>
    public bool PreserveReferences { get; set; }

    /// <summary>
    ///     If set to true, disable constructor validation.
    /// </summary>
    public bool DisableCtorValidation { get; set; }

    /// <summary>
    ///     If set to true, include this configuration in all derived types' maps.
    /// </summary>
    public bool IncludeAllDerived { get; set; }

    /// <summary>
    ///     使用converter进行映射，忽略作用在成员属性上的注解
    /// </summary>
    public Type? TypeConverter { get; set; }

    public void ApplyConfiguration(IMappingExpression mappingExpression)
    {
        if (ConstructUsingServiceLocator) mappingExpression.ConstructUsingServiceLocator();

        if (MaxDepth > 0) mappingExpression.MaxDepth(MaxDepth);

        if (PreserveReferences) mappingExpression.PreserveReferences();

        if (DisableCtorValidation) mappingExpression.DisableCtorValidation();

        if (IncludeAllDerived) mappingExpression.IncludeAllDerived();

        if (TypeConverter != null) mappingExpression.ConvertUsing(TypeConverter);
    }
}